#!/bin/bash -e

# Build and install patched version of adb, see
# https://rnd-gitlab-msc.huawei.com/rus-os-team/compilers/tasks/-/issues/1316

if [ "$1" != "--really-run-this-script" ]; then
    echo "WARNING: Please review the script before running it on a host system"
    exit 1
fi

source /etc/lsb-release
tee /etc/apt/sources.list.d/src.list <<EOF
deb-src https://nexus.devops-spb.rnd.huawei.com/repository/apt-proxy/ ${DISTRIB_CODENAME} main universe
EOF

apt-get update
apt-get install -y --no-install-recommends \
    debhelper \
    android-libboringssl-dev \
    libusb-1.0-0-dev

# Get package sources
mkdir /tmp/adb-rebuild
cd /tmp/adb-rebuild
# At now, fix the exact version of adb sources in case the surrounding
# lines of code change making this patch fail to apply.
apt-get source adb=1:8.1.0+r23-5ubuntu2
cd android-platform-system-core-*

# Apply patch & build
cat "$(dirname "$0")/adb_enable_shell_v2.patch" | patch -p1
touch debian/adb.1 # Pretend man page is already built
./debian/rules adb

# Install
cp *.so *.so.* /usr/lib/x86_64-linux-gnu/android/
cp adb/adb /usr/bin/
ldconfig

# Cleanup
cd /
rm -rf /tmp/adb-rebuild
rm /etc/apt/sources.list.d/src.list
apt-get clean
rm -rf /var/lib/apt/lists/*
